// miniprogram/pages/myBook/myBook.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    books: [],
    // 避免多一次请求
    isLoading: false
  },

  onLoad () {
    if (app.globalData.userInfo === undefined) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
    } else {
      this.loadBooks()
    }
  },

  onShow () {
    if (app.globalData.userInfo) {
      this.loadBooks()
    }
  },

  async loadBooks () {
    if (this.data.isLoading) return
    this.setData({
      isLoading: true
    })
    wx.showLoading({
      title: '书籍获取中...'
    })
    const books = await wx.cloud.callFunction({
      name: 'loadMyBooks'
    })
    books.result.forEach(item => {
      // 剩余小时数
      const rt = item.remainTime / 1000 / 60 / 60
      let day = 0
      let hour = 0
      if (rt > 24) {
        day = rt / 24
        hour = rt % 24
      } else {
        hour = rt
      }
      day = parseInt(day)
      hour = parseInt(hour)
      item.remainTime = `${ day === 0 ? '' : day + ' 天' } ${hour} 小时`
    })
    this.setData({
      books: books.result,
      isLoading: false
    })
    wx.hideLoading()
  },

  // 跳转到书籍详情页
  handleNavDetail (e) {
    const data = e.currentTarget.dataset.bookInfo
    wx.navigateTo({
      url: '/pages/bookDetail/bookDetail',
      events: {
        accepData (data) {
          console.log(data)
        }
      },
      async success (res) {
        const typesData = await wx.cloud.callFunction({
          name: 'loadTypes'
        })
        const types = typesData.result.data
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('accepData', {
          data,
          operate: 'manage',
          types
        })
      }
    })
  },
  // 续借
  async handleContinue (e) {
    wx.showLoading({
      title: '续借中...',
      mask: true
    })
    const book = e.currentTarget.dataset.bookInfo
    const { result } = await wx.cloud.callFunction({
      name: 'continueBook',
      data: book
    })
    if (result.status === 0) {
      this.loadBooks()
      wx.showToast({
        title: result.msg,
        icon: 'success'
      })
    } else {
      wx.hideLoading()
    }
  },
  // 归还
  async handleReturn (e) {
    wx.showLoading({
      title: '归还中...',
      mask: true
    })
    const book = e.currentTarget.dataset.bookInfo
    const { result } = await wx.cloud.callFunction({
      name: 'returnBook',
      data: book
    })
    if (result.status === 0) {
      this.loadBooks()
      wx.showToast({
        title: result.msg,
        icon: 'success'
      })
      const newUserBooks = app.globalData.userInfo.books.filter(item => item.bookId !== book.bookId)
      app.globalData.userInfo.books = newUserBooks
    } else {
      wx.hideLoading()
    }
  }
})
